﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreBBS.Common;
using NetCoreBBS.Entities;
using NetCoreBBS.Interfaces;

namespace BBSPhoneNumberPolicy.Controllers
{
    [Route("[controller]")]
    public class CustomerController : Controller
    {
        private readonly ICustomerRepository _customerRepository;
        private readonly ITopicRepository _topicRepository;

        public CustomerController(ICustomerRepository customerRepository,
            ITopicRepository topicRepository)
        {
            _customerRepository = customerRepository;
            _topicRepository = topicRepository;
        }
        
        [Authorize]
        [HttpGet("[action]")]
        public IActionResult Index()
        {
            var pagesize = 20;
            var pageindex = 1;

            if (!string.IsNullOrEmpty(Request.Query["page"]))
                pageindex = Convert.ToInt32(Request.Query["page"]);

            var res = _customerRepository.PageList(pagesize, pageindex);
            
            ViewBag.PageIndex = pageindex;
            ViewBag.Customers = res.List;
            return View();
        }

        [HttpGet("[action]")]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost("[action]")]
        public IActionResult Create(Customer customer)
        {
            if (ModelState.IsValid)
            {
                //是否合格的手机号
                Regex regexAll = new Regex(@"^(13[0-9]|145|14[78]|15[0-3]|15[5-9]|17[6-8]|18[0-9])[0-9]{8}$");
                if (regexAll.IsMatch(customer.PhoneNumber))
                {
                    customer.ArrivedTime = DateTime.Now;
                    var c = _customerRepository.Table.Where(x => x.PhoneNumber == customer.PhoneNumber).FirstOrDefault();
                    if(c == null)
                    {
                        _customerRepository.Add(customer);
                    }
                    else
                    {
                        c.ArrivedTime = DateTime.Now;
                        _customerRepository.Edit(c);
                    }

                    Regex regexUnicom = new Regex(@"^(13[0-2]|145|15[56]|176|18[56])[0-9]$");
                    if (regexUnicom.IsMatch(customer.PhoneNumber))
                    {
                        Console.Write("lt");
                    }
                    else
                    {
                        var topic = _topicRepository.TableNoTracking.Where(x => x.Type == Enums.TopicType.Good).FirstOrDefault();
                        if(topic != null)
                        {
                            return RedirectToAction("details", "topic", new { id = topic.Id });
                        }
                    }

                }
            }
            return View();
        }
    }
}